package com.imooc.business.core.executor.collect;

import com.imooc.module.collect.enums.DimensionEnum;
import com.imooc.module.collect.enums.PeriodEnum;
import jakarta.annotation.PostConstruct;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author Tim
 * @Description: 采集模板类
 * @Version 1.0
 */
@Component
public class CollectCommon {

    private final List<CollectProcess> collectProcess;
    @Qualifier("defaultCollectProcess")
    @Setter(onMethod_ = @Autowired)
    private CollectProcess defaultCollectProcess;

    public CollectCommon(List<CollectProcess> collectProcess) {
        this.collectProcess = collectProcess;
    }

    private static Map<String, CollectProcess> collectProcessMap = new ConcurrentHashMap<>();

    @PostConstruct
    public void init() {
        Optional.ofNullable(collectProcess).stream().flatMap(Collection::stream).
                forEach(collectProcess -> collectProcessMap.put(buildKey(collectProcess), collectProcess));
    }

    /**
     * 获取执行的采集器
     * @param dimensionEnum
     * @param periodEnum
     * @return
     */
    public CollectProcess getProcess(DimensionEnum dimensionEnum, PeriodEnum periodEnum) {
        CollectProcess process = collectProcessMap.get(buildKey(dimensionEnum, periodEnum));
        if (Objects.isNull(process)) {
            return defaultCollectProcess;
        }
        return process;
    }

    private String buildKey(CollectProcess collectProcess) {
        return buildKey(collectProcess.supportDimension(), collectProcess.supportPeriod());
    }

    private String buildKey(DimensionEnum dimensionEnum, PeriodEnum periodEnum) {
        return dimensionEnum + "_" + periodEnum;
    }
}
